//===----------------------------------------------------------------------===//
//
//                         BusTub
//
// index_scan_executor.cpp
//
// Identification: src/execution/index_scan_executor.cpp
//
// Copyright (c) 2015-19, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "execution/executors/index_scan_executor.h"

namespace bustub {
IndexScanExecutor::IndexScanExecutor(ExecutorContext *exec_ctx, const IndexScanPlanNode *plan)
    : AbstractExecutor(exec_ctx),
      plan_(plan),
      tree_(dynamic_cast<BPlusTreeIndexForTwoIntegerColumn *>(
          exec_ctx_->GetCatalog()->GetIndex(plan_->GetIndexOid())->index_.get()))

{}

void IndexScanExecutor::Init() {
  LOG_DEBUG("Init");
  iterator_ = tree_->GetBeginIterator();
}

auto IndexScanExecutor::Next(Tuple *tuple, RID *rid) -> bool {
  LOG_DEBUG("Next");
  while (!iterator_.IsEnd()) {  // 不等于结束的话, 可以查询出
    LOG_DEBUG("Next1");

    // 从iterator_ 获取 tuple 和 rid
    *rid = (*iterator_).second;  // 返回的是 rid
    LOG_DEBUG("rid=%s", rid->ToString().c_str());
    auto table_info =
        exec_ctx_->GetCatalog()->GetTable(exec_ctx_->GetCatalog()->GetIndex(plan_->GetIndexOid())->table_name_);
    auto tuple_and_meta = table_info->table_->GetTuple(*rid);
    if (!tuple_and_meta.first.is_deleted_) {
      *tuple = tuple_and_meta.second;
      LOG_DEBUG("tuple=%s", tuple->ToString(&GetOutputSchema()).c_str());
      ++iterator_;
      return true;
    }
    LOG_DEBUG("Next3");

    ++iterator_;
  }
  return false;
}

}  // namespace bustub
